package com.gz.qqserveer;

import com.gz.common.Message;
import com.gz.common.MessageType;
import com.gz.common.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

public class QQserver {
    private ServerSocket serverSocket=null;

    //这里也可以用ConcurrentHashMap,可以处理并发的集合，没有线程安全问题
//    static private ConcurrentHashMap<String,User> validUsers=new ConcurrentHashMap<>();//保存用户的数组
    static private HashMap<String,User> validUsers=new HashMap<>();//保存用户的数组
    static private ConcurrentHashMap<String, ArrayList<Message>> offlineMessages=new ConcurrentHashMap<>();//保存离线消息的数组
    static{//在静态代码块里
            validUsers.put("100",new User("100","123456"));
            validUsers.put("200",new User("100","123456"));
            validUsers.put("张无忌",new User("张无忌","123456"));
            validUsers.put("孙悟空",new User("孙悟空","123456"));
            validUsers.put("gz",new User("gz","123456"));
    }


    public static ConcurrentHashMap<String, ArrayList<Message>> getOfflineMessages() {
        return offlineMessages;
    }

    private void sendOfflineMessage(String userId){
        if(offlineMessages.containsKey(userId)){
            ArrayList<Message> messages=offlineMessages.get(userId);
            for(Message message:messages){
                try {
                    ObjectOutputStream oops = new ObjectOutputStream(MangeServerConnectClientThread.getServerConnectClientThread(
                            message.getReceiver()).getSocket().getOutputStream());
                    oops.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            offlineMessages.remove(userId);
        }
    }


    //验证用户名和密码方法
    private boolean checkUser(String userId, String password){
        User user=validUsers.get(userId);
        if(user==null){
            return false;
        }
        if(!user.getPassword().equals(password)){
            return false;
        }
        return true;
    }

    public QQserver(){
        try {
            System.out.println("服务器在9999端口监听...");
            new Thread(new SendNewsToAll()).start();//启动推送新闻的线程
            serverSocket=new ServerSocket(9999);

            while(true){
                Socket socket=serverSocket.accept();
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                User user=(User)ois.readObject();//接收客户端发送的用户账号密码

                //发送用户信息
                ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
                Message message=new Message();
                if(checkUser(user.getUserId(),user.getPassword())){
                    message.setMestype(MessageType.MESSAGE_LOGIN_SUCCEED);
                    oos.writeObject(message);
                    //对于服务器来说，客户端线程很多，所以加上userId来识别是哪一个客户端线程
                    ServerConnectClientThread s = new ServerConnectClientThread(socket, user.getUserId());
                    s.start();
                    MangeServerConnectClientThread.addServerConnectClientThread(user.getUserId(), s);
                    sendOfflineMessage(user.getUserId());
                }
                else {//登录失败
                    System.out.println("用户 id= "+user.getUserId()+
                            " password= "+user.getPassword()+" 验证失败");
                    message.setMestype(MessageType.MESSAGE_LOGIN_FAILED);
                    oos.writeObject(message);
                    socket.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
            finally {
            //如果服务器退出while循环，说明服务器不再监听，因此关闭ServerSocket
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
